﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using PSE.Deployment.SetupBase.Configuration;
using PSE.Deployment.SetupBase.Parameter;
using PSE.Deployment.Engine.CustomExceptions;
using PSE.Deployment.Engine.Interfaces;

namespace PSE.Deployment.SetupBase.Steps
{
    public class InstallCertificate : SetupStep<Configuration.Actions.InstallCertificate>
    {
        public InstallCertificate(IStepGroup parent, Group group, Configuration.Actions.InstallCertificate action, Parameter.Enums.SetupMode setupMode)
            : base(parent, group, action, setupMode)
        {
            this.ResetProgress(Action.Certificates.Count);
        }

        public override void Execute()
        {
            this.ResetProgress(Action.Certificates.Count);

            if (this.SetupMode == Parameter.Enums.SetupMode.Install)
            {
                InstallCertificates();
            }
            else if (this.SetupMode == Parameter.Enums.SetupMode.Uninstall)
            {
                UninstallArtefacts();
            }
        }

        public override void Undo()
        {
            if (this.SetupMode == Parameter.Enums.SetupMode.Install)
                UninstallArtefacts();
        }

        private void InstallCertificates()
        {
            foreach (Configuration.Certificate certificate in Action.Certificates)
            {
                if (this.IsStopped())
                    break;

                string fileName = SetupMainFactory.GetInstance().Parameter.InstallationPath + certificate.File.Destination + certificate.File.FileName;

                try
                {
                    this.IncrementProgress(fileName);

                    PSE.Deployment.Util.Certificate.AddCertificate(certificate.StoreName, StoreLocation.LocalMachine, fileName, PSE.Deployment.Util.EncryptDecrypt.Decrypt(certificate.Password));

                    this.AddUsedBy(certificate.File.FileName);
                }
                catch
                {
                    this.DecrementProgress(fileName);
                    throw;
                }
            }
        }

        protected override void UninstallArtefact(string artefactName)
        {
            Configuration.Certificate certificate = Action.Certificates.Find(c => c.File.FileName == artefactName);

            if (certificate != null)
            {
                string fileName = SetupMainFactory.GetInstance().Parameter.InstallationPath + certificate.File.Destination + certificate.File.FileName;

                PSE.Deployment.Util.Certificate.RemoveCertificate(certificate.StoreName, StoreLocation.LocalMachine, fileName, PSE.Deployment.Util.EncryptDecrypt.Decrypt(certificate.Password));
            }
        }
    }
}
